/*服务器模板创建日期2016年11月4日15:54:55 Myweb*/
const express = require('express');
const app = express();
const fs = require('fs');
const port = 3000;
const watcher = require('filewatcher');
const nunjucks = require('nunjucks');
const watch = watcher();
const ws = require('nodejs-websocket');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
//工程模式
nunjucks.configure('html', {
    autoescape: true,
    express: app,
    noCache: process.env.NODE_ENV !== 'production'
});

const os = require('os');
//获取服务器IP地址
const getIPAddress = function () {
    var ifaces = os.networkInterfaces();
    var ip = '';
    for (var dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (ip === '' && details.family === 'IPv4' && !details.internal) {
                ip = details.address;
                return;
            }
        });
    }
    return ip || "127.0.0.1";
};


//工程目录内部路由处理

app.get('*', function (req, res) {
    var dirList = [];
    var url = decodeURI(req.url.substr(1));
    var dir = fs.readdirSync('./html');
    dir.forEach(function (e) {
        if (e.indexOf('.html') > -1) {
            dirList.push(e);
        }
    });


    //一般路由，渲染对应页面
    if (dirList.indexOf(url) > -1) {
        res.render(url, {
                title: url,
                links: dirList
            }
        );
    }
    else {
        if (url == '') {
            res.render('./system/default.html', {title: '首页', links: dirList})
        }
        else if (url == 'dist') {
            console.log('-'.repeat(30));
            var pageHtml = [];
            dirList.forEach(function (e, i) {
                nunjucks.render(e, {title: e}, function (err, data) {
                    pageHtml.push(data);
                    if (i == dirList.length - 1) {
                        dist(dirList, pageHtml, function () {
                            console.log('静态文件生成完成');
                            res.render('system/dist.html', {
                                links: dirList
                            });
                        })
                    }
                });
            });
        }
        else if (url == 'dictionary.html') {
            res.render('system/dictionary.html', {
                links: dirList
            })
        }
        else {
            res.render('system/404.html', {
                links: dirList
            })
        }
    }
});
//启动提示
app.listen(port, function () {
    const ip = getIPAddress();
    console.log('服务器启动成功！\n地址:' + ip + ':' + port);
});
//文件变动监测

const watchHtml = fs.readdirSync('./');
const watchSrc = fs.readdirSync('./');

watchHtml.forEach(function (e) {
    watch.add('./html/' + e);
});
watchSrc.forEach(function (e) {
    watch.add('./src/' + e);
});


watch.on('change', function (file, stat) {
    if (!server.connections.length) {
        console.log('警告：没有活动页面或页面未连接！');
        c.exec('open http://127.0.0.1:3000');
    }
    else {
        if (file.indexOf('css') > -1) {
            broadcast(server, 'css');
            console.log('修改CSS文件，样式表已更新', new Date().toLocaleTimeString());
        }
        else {
            broadcast(server, 'reload');
            console.log('修改HTML文件，页面重加载', new Date().toLocaleTimeString());
        }
        if (!stat) console.log('文件已移除');

    }

});
const server = ws.createServer(function (conn) {
    conn.on('text', function (msg) {
        console.log('页面："' + msg + '"进入监测范围');
    });
    conn.on("close", function (code, reason) {
    });
    conn.on('error', function (err) {
        console.log('Chrome客户端离开了');
    })

}).listen(3001);

function broadcast(server, msg) {
    server.connections.forEach(function (conn) {
        conn.sendText(msg);
    })
}

//构建静态html函数
function dist(fileArr, dataArr, cbk) {
    //存在dist目录就删除dist
    fs.existsSync('./dist') ? rmFolder('./dist') : 0;
    //新建文件夹
    fs.mkdirSync('./dist');
    fileArr.forEach(function (e, i) {
        fs.writeFile('./dist/' + e + '.html', dataArr[i]);
        if (i == fileArr.length - 1) {
            cbk();
        }
    });
    //读取资源目录
    fs.readdir('./src/', function (err, ls) {
        if (err) {
            console.log(err)
        }
    });
}

//删除文件夹
function rmFolder(path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function (file) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                rmFolder(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}

module.exports=app;
